package com.cloud.user.biz.login;

import com.cloud.common.R;
import com.cloud.excption.BizException;
import com.cloud.mall.user.TbMember;
import com.cloud.user.biz.dto.LoginDto;
import com.cloud.user.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/7/7 11:27
 * @Desc
 * @Remarks
 */
@Slf4j
public abstract class AbstractLogin implements Login {

    public static ConcurrentHashMap<Integer, AbstractLogin> loginMap = new ConcurrentHashMap<>();

    public AbstractLogin() {
        loginMap.put(getLoginType(), this);
    }

    abstract protected Integer getLoginType();

    /**
     * 通过子类去完成验证
     *
     * @param authLoginDto
     */
    public abstract TbMember validate(LoginDto authLoginDto);

    /**
     * 登录校验
     *
     * @param authLoginDto
     */
    public abstract TbMember doProcessor(LoginDto authLoginDto);

    @Override
    public R doLogin(LoginDto loginDto) {
        log.info("begin AbstractLogin.doLogin:" + loginDto);
        try {
            TbMember member = validate(loginDto); //第一步完成验证
            doProcessor(loginDto);
            Map<String, Object> map = new HashMap<>();
            map.put("id", member.getId());
            map.put("name", member.getUsername());
            Long nowTimeStamp = System.currentTimeMillis();
            map.put("timestamp", nowTimeStamp);
            String s = TokenUtils.generatorToken(map);
            return new R.Builder().buildCustomize(200, s);
        } catch (BizException e) {
            e.printStackTrace();
            return new R.Builder().buildCustomize(e.getCode() == null ? 500 : Integer.parseInt(e.getCode()), e.getMsg());
        } finally {
        }
    }
}
